<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品工序配置 - {{ productInfo.name }}</span>
          <div class="right-menu">
            <el-button icon="Back" @click="goBack">返回</el-button>
            <el-button 
              type="primary" 
              @click="saveProcessConfig" 
              v-hasPermi="['qep:product:edit']"
            >保存配置</el-button>
          </div>
        </div>
      </template>

      <el-descriptions title="产品信息" :column="3" border size="small">
        <el-descriptions-item label="产品编码">{{ productInfo.code }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ productInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="产品分类">{{ productInfo.categoryName }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">工序流程配置</el-divider>

      <div class="process-config">
        <div class="process-toolbox">
          <div class="toolbox-title">工序列表</div>
          <div class="search-box">
            <el-input
              v-model="searchTerm"
              placeholder="搜索工序"
              prefix-icon="Search"
              clearable
            />
          </div>
          <el-scrollbar height="400px">
            <draggable
              :list="availableProcesses"
              :group="{ name: 'processes', pull: 'clone', put: false }"
              item-key="id"
              :sort="false"
              :clone="cloneProcess"
            >
              <template #item="{ element }">
                <div class="process-item">
                  <div class="process-icon">
                    <el-icon><operation /></el-icon>
                  </div>
                  <div class="process-info">
                    <div class="process-name">{{ element.name }}</div>
                    <div class="process-desc">{{ element.typeName }} | {{ element.standardTime }}分钟</div>
                  </div>
                </div>
              </template>
            </draggable>
          </el-scrollbar>
        </div>

        <div class="process-flow">
          <div class="flow-title">工序流程</div>
          <el-empty v-if="productProcesses.length === 0" description="请从左侧拖拽工序到此处" />
          <draggable
            v-else
            :list="productProcesses"
            group="processes"
            item-key="id"
            handle=".drag-handle"
            class="process-flow-container"
          >
            <template #item="{ element, index }">
              <div class="flow-process-item">
                <div class="flow-process-order">{{ index + 1 }}</div>
                <div class="flow-process-content">
                  <div class="flow-process-header">
                    <div class="drag-handle"><el-icon><operation /></el-icon></div>
                    <div class="flow-process-name">{{ element.name }}</div>
                    <div class="flow-process-actions">
                      <el-button 
                        type="primary" 
                        link
                        icon="Edit" 
                        @click="editProcess(element, index)"
                      ></el-button>
                      <el-button 
                        type="danger" 
                        link
                        icon="Delete" 
                        @click="removeProcess(index)"
                      ></el-button>
                    </div>
                  </div>
                  <div class="flow-process-body">
                    <div class="flow-process-prop">
                      <span class="prop-label">工序类型:</span>
                      <span class="prop-value">{{ element.typeName }}</span>
                    </div>
                    <div class="flow-process-prop">
                      <span class="prop-label">标准工时:</span>
                      <span class="prop-value">{{ element.standardTime }}分钟</span>
                    </div>
                    <div v-if="element.description" class="flow-process-prop">
                      <span class="prop-label">描述:</span>
                      <span class="prop-value">{{ element.description }}</span>
                    </div>
                    <div v-if="element.parameters && element.parameters.length > 0" class="flow-process-params">
                      <div class="params-title">参数要求:</div>
                      <el-tag v-for="param in element.parameters" :key="param.name" size="small" class="param-tag">
                        {{ param.name }}: {{ param.value }} {{ param.unit }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </draggable>

          <div class="flow-summary" v-if="productProcesses.length > 0">
            <div class="summary-item">
              <div class="summary-label">工序总数:</div>
              <div class="summary-value">{{ productProcesses.length }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">总工时:</div>
              <div class="summary-value">{{ getTotalTime() }}分钟</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 工序编辑对话框 -->
    <el-dialog
      v-model="processDialog.visible"
      :title="processDialog.title"
      width="500px"
      append-to-body
    >
      <el-form ref="processForm" :model="processDialog.data" label-width="100px">
        <el-form-item label="工序名称">
          <el-input v-model="processDialog.data.name" disabled />
        </el-form-item>
        <el-form-item label="工序类型">
          <el-input v-model="processDialog.data.typeName" disabled />
        </el-form-item>
        <el-form-item label="标准工时">
          <el-input-number v-model="processDialog.data.standardTime" :min="1" :precision="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="工序描述">
          <el-input v-model="processDialog.data.description" type="textarea" rows="2" />
        </el-form-item>
        <el-divider content-position="center">参数配置</el-divider>
        <div class="parameter-list">
          <div v-for="(param, index) in processDialog.data.parameters" :key="index" class="parameter-item">
            <el-row :gutter="10">
              <el-col :span="7">
                <el-input v-model="param.name" placeholder="参数名称" />
              </el-col>
              <el-col :span="7">
                <el-input v-model="param.value" placeholder="参数值" />
              </el-col>
              <el-col :span="7">
                <el-input v-model="param.unit" placeholder="单位" />
              </el-col>
              <el-col :span="3">
                <el-button type="danger" icon="Delete" circle @click="removeParameter(index)" />
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" icon="Plus" @click="addParameter" style="margin-top: 10px;">添加参数</el-button>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="saveProcessEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getProduct } from "@/api/qep/product";
import { listProcess } from "@/api/qep/process";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Operation } from '@element-plus/icons-vue';
import draggable from 'vuedraggable';

const route = useRoute();
const router = useRouter();

// 产品信息
const productInfo = ref({});
// 所有可用工序
const allProcesses = ref([]);
// 搜索关键词
const searchTerm = ref('');
// 产品已配置的工序
const productProcesses = ref([]);

// 工序编辑对话框
const processDialog = reactive({
  visible: false,
  title: '',
  data: {},
  index: -1
});

// 可用的工序列表，根据搜索筛选
const availableProcesses = computed(() => {
  if (!searchTerm.value) {
    return allProcesses.value;
  }
  return allProcesses.value.filter(p => 
    p.name.toLowerCase().includes(searchTerm.value.toLowerCase()) ||
    p.code.toLowerCase().includes(searchTerm.value.toLowerCase()) ||
    p.typeName.toLowerCase().includes(searchTerm.value.toLowerCase())
  );
});

// 获取产品详情
function getProductDetail(id) {
  getProduct(id).then(response => {
    productInfo.value = response.data || {};
    // TODO: 从后端获取产品工序配置
    // 为了演示，我们使用模拟数据
    initProductProcesses();
  });
}

// 获取所有工序
function getAllProcesses() {
  listProcess({ pageSize: 100 }).then(response => {
    allProcesses.value = response.rows || [];
  });
}

// 初始化产品工序（模拟数据）
function initProductProcesses() {
  // 在实际应用中，应该从后端获取当前产品的工序配置
  productProcesses.value = [
    { 
      id: 101, 
      code: 'P001', 
      name: '下料', 
      typeName: '机加工', 
      standardTime: 30, 
      description: '按图纸要求下料',
      parameters: [
        { name: '材料型号', value: 'Q235', unit: '' },
        { name: '下料尺寸', value: '300x200', unit: 'mm' }
      ]
    },
    { 
      id: 102, 
      code: 'P002', 
      name: '车削', 
      typeName: '机加工', 
      standardTime: 60, 
      description: '使用车床进行外形加工',
      parameters: [
        { name: '精度要求', value: '0.01', unit: 'mm' }
      ]
    }
  ];
}

// 复制工序（拖拽时使用）
function cloneProcess(process) {
  // 为新工序生成唯一ID
  const newProcess = { ...process };
  newProcess.id = Date.now();
  // 默认添加空参数列表
  if (!newProcess.parameters) {
    newProcess.parameters = [];
  }
  return newProcess;
}

// 编辑工序
function editProcess(process, index) {
  processDialog.title = '编辑工序 - ' + process.name;
  processDialog.data = JSON.parse(JSON.stringify(process));
  processDialog.index = index;
  processDialog.visible = true;
}

// 保存工序编辑
function saveProcessEdit() {
  // 更新工序列表中的工序
  productProcesses.value[processDialog.index] = processDialog.data;
  processDialog.visible = false;
  ElMessage.success('工序配置已更新');
}

// 移除工序
function removeProcess(index) {
  ElMessageBox.confirm('确定要移除此工序吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    productProcesses.value.splice(index, 1);
    ElMessage.success('工序已移除');
  }).catch(() => {});
}

// 添加参数
function addParameter() {
  if (!processDialog.data.parameters) {
    processDialog.data.parameters = [];
  }
  processDialog.data.parameters.push({ name: '', value: '', unit: '' });
}

// 移除参数
function removeParameter(index) {
  processDialog.data.parameters.splice(index, 1);
}

// 计算总工时
function getTotalTime() {
  return productProcesses.value.reduce((sum, process) => sum + (process.standardTime || 0), 0);
}

// 保存工序配置
function saveProcessConfig() {
  // TODO: 调用后端API保存工序配置
  console.log('保存工序配置', productProcesses.value);
  ElMessage.success('工序配置保存成功');
}

// 返回上一页
function goBack() {
  router.go(-1);
}

onMounted(() => {
  if (route.query.id) {
    getProductDetail(route.query.id);
    getAllProcesses();
  }
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-menu {
  margin-left: auto;
}

.process-config {
  display: flex;
  margin-top: 20px;
  gap: 20px;
}

.process-toolbox {
  width: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.toolbox-title, .flow-title {
  padding: 10px;
  font-weight: bold;
  border-bottom: 1px solid #dcdfe6;
  background-color: #f2f6fc;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}

.process-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: move;
  background-color: white;
  transition: background-color 0.3s;
}

.process-item:hover {
  background-color: #ecf5ff;
}

.process-icon {
  margin-right: 10px;
  color: #409EFF;
}

.process-info {
  flex-grow: 1;
}

.process-name {
  font-weight: bold;
}

.process-desc {
  font-size: 12px;
  color: #909399;
}

.process-flow {
  flex-grow: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.process-flow-container {
  min-height: 400px;
  padding: 10px;
}

.flow-process-item {
  display: flex;
  margin-bottom: 15px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

.flow-process-order {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  background-color: #409EFF;
  color: white;
  font-weight: bold;
}

.flow-process-content {
  flex: 1;
  padding: 10px;
}

.flow-process-header {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.drag-handle {
  cursor: move;
  margin-right: 8px;
  color: #909399;
}

.flow-process-name {
  flex: 1;
  font-weight: bold;
}

.flow-process-actions {
  display: flex;
  gap: 8px;
}

.flow-process-body {
  padding-top: 8px;
}

.flow-process-prop {
  margin-bottom: 5px;
  font-size: 13px;
}

.prop-label {
  color: #606266;
  margin-right: 5px;
}

.prop-value {
  color: #303133;
}

.flow-process-params {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #ebeef5;
}

.params-title {
  margin-bottom: 5px;
  font-size: 13px;
  color: #606266;
}

.param-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.flow-summary {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  gap: 20px;
  border-top: 1px solid #dcdfe6;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-label {
  margin-right: 5px;
  color: #606266;
}

.summary-value {
  font-weight: bold;
  color: #409EFF;
}

.parameter-item {
  margin-bottom: 10px;
}

.el-divider {
  margin: 20px 0;
}
</style> 